<template>
  <view class="common pos-r changeNickname">
    <view class="pos-a z-0 wp-100" :class="env === 'H5' ? 'bg-yel' : 'bg-lg'" :style="globalData.barStyle" />
    <u-navbar :fixed="false">
      <u-icon slot="left" name="arrow-left" :color="env === 'H5' ? '#fff' : '#000'" size="19" @tap="navigateBack" />
      <view slot="center" :class="env === 'H5' ? 'c-fff' : 'c-bla'">更改昵称</view>
    </u-navbar>
    <view class="main">
      <view class="content bg-gry">
        <view class="d-f pv-12 ph-24 bg-whi">
          <view class="c-666 fs-30 lh-72 w-140">昵称</view>
          <u--input ref="input" v-model="userInfo.nickName" placeholder="请输入昵称" border="false" class="wc-280" maxlength="20" @confirm="saveNickname" />
        </view>
        <view class="bdb" />
      </view>
      <view class="footer">
        <u-button type="primary" text="保存" @tap="saveNickname" shape="circle" color="#FEA20D" :throttleTime="2000" />
      </view>
    </view>
  </view>
</template>

<script>
import commonMxins from '@/mixins/common.js';

export default {
  mixins: [commonMxins],
  data() {
    return {
      userInfo: uni.getStorageSync('userInfo') || {},
    };
  },
  methods: {
    // 保存昵称
    async saveNickname() {
      // 去除前后空格
      const trimmedNickname = this.nickName.trim();
      if (!trimmedNickname) {
        uni.showToast({ title: '昵称不能为空', icon: 'none' });
        return;
      }
      const res = await this.$request({ url: '/app/appUser/updateNickName', data: { nickName: this.userInfo.nickName } });

      if (res.code === 200) {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo) {
          const parsedUserInfo = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo;
          parsedUserInfo.nickName = trimmedNickname;
          parsedUserInfo.nickName = trimmedNickname; // 同时更新可能的不同字段名
          uni.setStorageSync('userInfo', parsedUserInfo);
        }
        uni.showToast({ title: '修改成功', icon: 'success', duration: 2000 });
        await this.$async.delay(2000);
        uni.navigateBack({ delta: 1 });
      } else {
        uni.showToast({ title: res.msg || '修改失败', icon: 'none' });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.changeNickname {
  .main {
    .content {
      height: calc(100% - 67px);
    }
  }
}
</style>
